<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="角色编号">
          <el-input v-model="formInline.strRolenum" placeholder="角色编号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit()">查询</el-button>
          <el-button type="primary" icon="el-icon-edit" @click="addRole(form)">添加</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-dialog :title="dialogTitleType" :visible.sync="dialogFormVisible" res="result">
      <el-form ref="form" :model="form" :rules="rules" label-width="100">
        <el-row :gutter="40">
          <el-col :span="10">
            <el-form-item prop="strRolename" label="角色名称">
              <el-input v-model="form.strRolename" placeholder="角色名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="iOrgsysnum" label="所属机构">
              <el-cascader
                v-model="form.iOrgsysnum"
                :show-all-levels="false"
                :options="optionslist"
                :props="{ multiple: true, emitPath:false,checkStrictly: true,expandTrigger: 'hover',value:'strOrgnum',label:'strOrgname',children: 'yhlist' }"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item prop="roleMenu" label="角色权限">
              <el-cascader
                v-model="form.roleMenu"
                :options="menuRoles"
                collapse-tags
                :props="{
              expandTrigger: 'hover',
              value: 'menuId',
              label: 'strMenu',
              children: 'icon',
              multiple: true
            }"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="succ('form')">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="角色详情" :visible.sync="dialogFormDatil">
      <el-form ref="form" :model="formdatil" label-width="100">
        <el-row :gutter="40">
          <el-col :span="8">
            <el-form-item label="角色编号">
              <el-input v-model="formdatil.strRolenum" placeholder="角色编号" readonly />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="角色名称">
              <el-input v-model="formdatil.strRolename" placeholder="角色名称" readonly />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="角色权限">
          <el-input v-model="formdatil.strValue" type="textarea" readonly autosize />
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="strRolenum" label="角色编号" width="180" />
      <el-table-column prop="strRolename" label="角色姓名" width="180" />
      <el-table-column prop="strOrgName" label="所属机构" width="180" />
      <el-table-column prop="strValue" label="角色权限" width="180" :show-overflow-tooltip="true" />
      <el-table-column label="操作" min-width="200">
        <template slot-scope="{row}">
          <template v-if="iOrgsysnum === -1||row.iOrgsysnum === iOrgsysnum">
            <el-button type="info" size="mini" @click="selectRole(row)">查看</el-button>
            <el-button type="primary" size="mini" @click="updateRole(row)">修改</el-button>
            <el-button type="danger" size="mini" @click="DeleteRole(row)">删除</el-button>
          </template>
          <template v-else>
            <el-button type="info" size="mini" @click="selectRole(row)">查看</el-button>
          </template>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total>0"
      :total="total"
      :page.sync="pagenum"
      :limit.sync="limit"
      :layout="layout"
      @pagination="getRoleList"
    />
  </div>
</template>
<script>
import {
  getList,
  deleteRole,
  updRoleInfo,
  listRoleNum,
  listRoleAuth,
  addRoleInfo,
  queryUserRole
} from '@/api/system/system'
import { getOrglists } from '../../api/addTag'
import Pagination from '@/components/Pagination'
import { validatestrRolename } from '../../utils/validateForm'
import { mapGetters } from 'vuex'

export default {
  components: {
    Pagination
  },
  data() {
    return {
      formInline: {
        rolenum: ''
      },
      form: {
        strRolename: '',
        iOrgsysnum: '',
        roleMenu: ''
      },
      formdatil: {
        strRolenum: '',
        strRolename: '',
        strValue: ''
      },
      tableData: [],
      rules: {
        strRolename: [
          { required: true, validator: validatestrRolename, trigger: 'blur' }
        ],
        iOrgsysnum: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ],
        roleMenu: [{ required: true, message: '请选择权限', trigger: 'change' }]
      },
      dialogFormVisible: false,
      dialogTitleType: '新增角色',
      checkmenu: [],
      perms: [],
      dialogFormDatil: false,
      read: false,
      updatrow: '',
      RoleStrNums: [],
      menuRoles: [],
      strMenu: [],
      defaultProps: {
        children: 'icon',
        label: 'strMenu'
      },
      result: '',
      options: [],
      optionslist: [], // 所属机构有权限
      total: 0,
      limit: 5,
      pagenum: 1,
      currentpage: 1,
      layout: 'total, prev, pager, next, jumper'
    }
  },
  computed: {
    ...mapGetters(['iOrgsysnum'])
  },
  created() {
    this.getRoleList()
  },
  methods: {
    onSubmit() {
      var strRolenum = this.formInline.strRolenum
      getList({ rows: this.pagenum, strRolenum: strRolenum, iType: 0 }).then(
        res => {
          this.tableData = res && res.data
          this.total = !res ? 0 : res.total
        }
      )
    },
    DeleteRole(row) {
      console.log(row)
      this.$confirm(
        '此操作将永久删除角色：' + row.strRolename + ', 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(() => {
          deleteRole({ id: row.id }).then(res => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getRoleList()
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    selectRole(row) {
      this.formdatil.strRolename = row.strRolename
      this.formdatil.strRolenum = row.strRolenum
      this.formdatil.strValue = row.strValue
      this.dialogFormDatil = true
    },
    updateRole(row) {
      this.form.strRolename = ''
      this.form.iOrgsysnum = ''
      this.perms = []
      this.options = []
      this.updatrow = row
      this.form.strRolename = row.strRolename
      this.dialogTitleType = '修改角色'
      listRoleAuth().then(res => {
        this.menuRoles = res.data
      })
      queryUserRole({ iRolesysnum: row.iRolesysnum }).then(res => {
        // this.form.roleMenu = res.data.split(',').map(i => {
        //   return parseInt(i)
        // })
        const arr = []
        res.data.map(item => {
          arr.push(parseInt(item.STR_MENUOBJ) + ',' + parseInt(item.ID))
        })
        this.form.roleMenu = arr
      })
      this.form.iOrgsysnum = row.iOrgsysnum + ''
      this.form.id = row.id
      this.form.iRolesysnum = row.iRolesysnum
      this.read = true
      this.dialogFormVisible = true
    },
    getRoleList() {
      getList({
        rows: this.pagenum,
        iType: 0,
        iOrgsysnum: this.$store.getters.iOrgsysnum
      }).then(res => {
        this.tableData = res.data
        this.total = res.total
      })
      listRoleNum({ iType: 0 }).then(res => {
        this.RoleStrNums = res.strRoleNum
      })
      getOrglists({ iOrgnum: this.$store.getters.iOrgsysnum }).then(res => {
        if (this.$store.getters.iOrgsysnum === -1) {
          this.optionslist = res && res.data
        } else {
          this.optionslist.push(res.data)
        }
      })
    },
    succ(formName) {
      if (this.dialogTitleType === '修改角色') {
        this.form.iType = 0
        if (!(this.form.iOrgsysnum instanceof Array)) {
          let iOrgsysnum = []
          iOrgsysnum.push(this.form.iOrgsysnum)
          iOrgsysnum = iOrgsysnum.splice(-1)
          this.form.iOrgsysnum = iOrgsysnum[0]
        } else {
          let iOrgsysnum = this.form.iOrgsysnum
          iOrgsysnum = iOrgsysnum.splice(-1)
          this.form.iOrgsysnum = iOrgsysnum[0]
        }
        this.form.perms = JSON.stringify(this.form.roleMenu)
        this.$refs[formName].validate(valid => {
          if (valid) {
            updRoleInfo(this.form).then(res => {
              this.$message({
                type: 'success',
                message: '修改成功!'
              })
              this.dialogFormVisible = false
              this.$refs[formName].resetFields()
              this.getRoleList()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else if (this.dialogTitleType === '新增角色') {
        if (!(this.form.iOrgsysnum instanceof Array)) {
          let iOrgsysnum = []
          iOrgsysnum.push(this.form.iOrgsysnum)
          iOrgsysnum = iOrgsysnum.splice(-1)
          this.form.iOrgsysnum = iOrgsysnum[0]
        } else {
          let iOrgsysnum = this.form.iOrgsysnum
          iOrgsysnum = iOrgsysnum.splice(-1)
          this.form.iOrgsysnum = iOrgsysnum[0]
        }
        this.form.iType = 0
        this.form.perms = JSON.stringify(this.form.roleMenu)
        this.$refs[formName].validate(valid => {
          if (valid) {
            addRoleInfo(this.form).then(res => {
              this.$message({
                type: 'success',
                message: '新增成功!'
              })
              this.$refs[formName].resetFields()
              this.dialogFormVisible = false
              this.getRoleList()
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      }
    },
    addRole() {
      this.dialogTitleType = '新增角色'
      this.form.strRolename = ''
      this.options = []
      this.form.roleMenu = []
      listRoleAuth().then(res => {
        this.menuRoles = res.data
      })
      getOrglists({ iOrgnum: this.$store.getters.iOrgsysnum }).then(res => {
        this.options.push(res.data)
      })
      this.$nextTick(() => {
        this.$refs['form'].resetFields() // this.$refs.adduserform.resetFields();
      })
      this.dialogFormVisible = true
    }
  }
}
</script>
